import bpy

import sys, os
import b2cs
print("Loading B2CS")

assetId = os.environ["BlenderMeshTranscoder-id"]
object = os.environ["BlenderMeshTranscoder-object"]
filePath = os.environ["BlenderMeshTranscoder-path"]
dependencies = os.environ["BlenderMeshTranscoder-dependencies"]

try:
  print(dependencies)
  dependencies = dependencies.replace('\n', '').replace('\r', '').replace('u\'', '\'')
  print(dependencies)
  dependencies = eval(dependencies)
except:
  print("ERROR parsing dependencies")

for format, assets in dependencies.items():
  if format in ['image/png', 'image/jpg', 'image/jpeg', 'image/tga', 'image/blender']:
    for subName, tuple in assets.items():
      id, fileName = tuple
      resolved = False
      for image in bpy.data.images:
        if os.path.basename(image.filepath) == subName: #TODO: does this handle packed images?
          image.filepath = id
          print('i: Resolved dependency', subName, format, id)
          #Don't break, asset can be pointed too several times.
          resolved = True
      if not resolved: 
        print('W: UnResolved dependency', subName, format, id)


#Dont write out images.
def dummy(self, path):
  print('dummy image writer', path)
bpy.types.Image.save_export = dummy

  
if object in bpy.data.objects:
  def Write(fi):
    def write(data):
      fi.write(data+'\n')
    return write
    
  if not os.path.exists(os.path.dirname(filePath)):
    os.makedirs(os.path.dirname(filePath))
    
  fact = bpy.data.objects[object]
  fact.data.name = assetId
  fact = b2cs.io.object.Hierarchy(fact, None)
  fa = open(filePath, 'w')
  fact.AsCSLib(Write(fa), 1, texturePath='')
  fa.close()  
